# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

fastlane_version "2.86.0"

default_platform :ios

CONFIG_PATH = "../Client/Configuration"
LOCAL_PATH = "#{CONFIG_PATH}/Local"

platform :ios do
  before_all do |lane, options|
    # Verify clean repo by default
    unless options[:ignore_git_status]
      UI.message "Running git status check"
      ensure_git_status_clean(show_uncommitted_changes: true, show_diff: true)
    end
  end

  after_all do |lane, options|
    # If no uncommitted changes existed before running `lane`, reset any potential fastlane changes
    reset_git_repo(skip_clean: true) unless options[:ignore_git_status]

    clean_icons()
  end

  error do
    clean_icons()
  end

  desc "Run Unit Tests"
  lane :test do |options|
    sh("../Client/WebFilters/ContentBlocker/Lists/test-compile-all-lists.sh")
    run_tests(
      scheme: "Fennec",
      device: "iPhone 8",
      code_coverage: true,
      skip_testing: [
        "DataTests/BookmarkTests",
        "DataTests/CRUDProtocolsTests",
        "DataTests/CoreDataTestCase",
        "DataTests/DataControllerTests",
        "DataTests/DeviceTests",
        "DataTests/DomainTests",
        "DataTests/FaviconMOTests",
        "DataTests/HistoryTests",
        "DataTests/TabMOTests",
        "DataTests/FavoriteTests",
        "ClientTests/TabManagerTests/testQueryAddedTabs",
        "ClientTests/TabManagerTests/testQueryAddedPrivateTabs",
        "ClientTests/TabManagerTests/testQueryAddedMixedTabs",
        "ClientTests/UIImageViewExtensionsTests/testAsyncSetIcon",
        "ClientTests/UIImageViewExtensionsTests/testAsyncSetIconFail",
        "ClientTests/FingerprintProtectionTest/testFingerprintProtection",
        "ClientTests/TabSessionTests"
      ]
    )
  end

  desc "Creates a Brave Beta Release build for TestFlight."
  lane :beta do |options|
    set_build_number(options)

    # TODO: make name dynamic
    # build_name = "Brave#{get_client_version_number}(#{get_build_number})"
    build_name = "BraveBeta#{get_client_version_number}"

    UI.message "NAME: #{build_name}"

    carthage(
      platform: "iOS",
      cache_builds: true,
      configuration: "Release",
    )

    defaultParams = gym_params()
    overrideParams = {
      scheme: "FirefoxBeta",
      output_directory: "./builds/",
      output_name: "#{build_name}.ipa",
      export_method: "development",
      include_symbols: true,
      include_bitcode: true,
    }
    gym(defaultParams.merge!(overrideParams))

    testflight(
      username: sh("cat", "#{LOCAL_PATH}/AppleId"),
      ipa: "./builds/#{build_name}.ipa",
      skip_waiting_for_build_processing: true,
    )
  end

  desc "Create an archive to be uploaded to the App Store"
  lane :release do |options|
    set_build_number(options)

    carthage(
      platform: "iOS",
      cache_builds: true,
      configuration: "Release",
    )

    defaultParams = gym_params()
    overrideParams = {
      scheme: "Firefox",
      skip_package_ipa: true,
    }
    gym(defaultParams.merge!(overrideParams))
  end

  # Private helper methods ---------------------------------------

  desc "Returns the parameters that should be used in any fastlane build"
  lane :gym_params do
    {
      sdk: "iphoneos",
      clean: true,
      xcargs: "-allowProvisioningUpdates BRAVE_API_KEY=\"#{sh("head", "-1", "#{ENV['HOME']}/.brave-api-key")}\""
    }
  end

  desc "Updates the project's build number to be the next number acceptable by TestFlight. Takes the following arguments:"
  lane :set_build_number do |options|
    dateFormat = "%y.%m.%d.%H"
    # Allows minute override in case two betas within same hour are required
    dateFormat += ".%M" if options[:minutes_in_build_number]
    formattedBuildNumber = Time.now.getutc.strftime(dateFormat)
    sh("echo GENERATED_BUILD_ID=#{formattedBuildNumber} > #{LOCAL_PATH}/BuildId.xcconfig")
  end

  # TODO: Attempt action override on same name
  private_lane :get_client_version_number do
    buildIdFile = Xcodeproj::Config.new("#{CONFIG_PATH}/Base.xcconfig")
    buildId = buildIdFile.attributes['BRAVE_VERSION']

    # Traditionally, would pull version number via:
    # get_version_number(target: "Client")
    # This however does not work since we use xcconfigq variables and Fastlane does not seem to parse
    #   these very well (e.g. this returns the literal value: "$(BRAVE_VERSION)")
  end

  private_lane :get_client_build_number do
    buildIdFile = Xcodeproj::Config.new("#{LOCAL_PATH}/BuildId.xcconfig")
    buildId = buildIdFile.attributes['GENERATED_BUILD_ID']
  end

  private_lane :clean_icons do
    # Regardless of git flags, always want to forcefully reset icon changes
    reset_git_repo(files: ["Client/Assets/Images.xcassets/AppIcon*"], force: true)
  end

  override_lane :get_build_number do
    get_client_build_number()
  end

  lane :logtest do |options|
    UI.message "1: #{options[:one]}"

    foo = sh("cat", "#{LOCAL_PATH}/AppleId")
    UI.message foo
  end

end
